//
//  LiveViewController.m
//  RainbowFM
//
//  Created by Kratos on 14/12/9.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "LiveViewController.h"

#import "ProgramIntroducedViewController.h"
#import "CompereDetailsViewController.h"
#import "LeaveWordsViewController.h"
#import "RadioHelpLisViewController.h"

#import "KKSwitchBarView.h"
#import "RecommendRadioListView.h"
#import "PlayerView.h"
#import "RadioView.h"
#import <MarqueeLabel/MarqueeLabel.h>

#import "ProgramModel.h"
#import "HelpModel.h"
#import "CompereModel.h"
#import "ADModel.h"

@interface LiveViewController ()<UITableViewDataSource,UITableViewDelegate,KKSwitchBarViewDelegate,RecommendRadioListViewDelegate,RadioViewDelegate>

@property (nonatomic , weak) IBOutlet UIView *playContentView;
@property (nonatomic , weak) IBOutlet UITableView *tableview;
@property (nonatomic , weak) IBOutlet MarqueeLabel *adLabel;

@property (nonatomic , strong) PlayerView *playerView;
@property (nonatomic , strong) RadioView *radioView;
@property (nonatomic , strong) KKSwitchBarView *switchBarView;//类型选择栏
@property (nonatomic , strong) RecommendRadioListView *radioListView;//全部栏目列表

@property (nonatomic , strong) ProgramItem *currentProgram;//当前节目

@property (nonatomic , strong) NSMutableDictionary *otherInfoDic;//留言或便民信息
@property (nonatomic , assign) NSInteger otherInfoType;//定位留言或便民信息

@property (nonatomic , strong) NSMutableArray *topADs;//顶部广告
@property (nonatomic , assign) NSInteger topadIndex;//当前底部广告位置
@property (nonatomic , strong) NSTimer *topadTimer;//当前广告时间间隔


@property (nonatomic , strong) NSMutableArray *buttomADs;//底部广告

@end

@implementation LiveViewController
-(void)awakeFromNib
{
    [self.navigationController setNavigationBarHidden:YES];
    
    _otherInfoDic = [NSMutableDictionary dictionary];
    [self initOtherInfoDic:0];
    [self initOtherInfoDic:1];
    
    _topADs = [NSMutableArray array];
    _buttomADs = [NSMutableArray array];
    
    _currentProgram = [ProgramItem new];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(magnifyAVPlayer:) name:kRFMNotificationAVMagnified object:nil];
    
    //初始化广告
    [_adLabel setScrollDuration:10.f];
    [_adLabel setFadeLength:10.f];
    
    [self initializeTableHeaderView];
    [self initializeTableFooterView];
    
    [self creatPlayView];
    
    [self updateLiveData];
    [self updateADList];
    [self updateTopADList];
    // Do any additional setup after loading the view.
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    
    [self starTopAD];
    
    if (_playerView) {
        [_playerView play];
    }
    
    if (_radioView) {
        [_radioView play];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self stopTopAD];
    
    if (_playerView) {
        [_playerView pause];
    }
    
    if (_radioView) {
        [_radioView pause];
    }
    
    [self.navigationController setNavigationBarHidden:NO];
    
    [SVProgressHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 更新数据
-(void)initOtherInfoDic:(int)index
{
    if (index == 0) {
        [_otherInfoDic setObject:@[[LeaveWordItem new],[LeaveWordItem new],[LeaveWordItem new]] forKey:@"0"];
    }else{
        [_otherInfoDic setObject:@[[HelpItem new],[HelpItem new],[HelpItem new]] forKey:@"1"];
    }
}

-(void)insertOtherInfoData:(NSArray *)data index:(int)index
{
    [self initOtherInfoDic:index];
    NSMutableArray *list = [[_otherInfoDic objectForKey:_F(@"%d",index)] mutableCopy];
    NSInteger i = 0;
    for (id item in data) {
        [list replaceObjectAtIndex:i withObject:item];
        i++;
    }
    [_otherInfoDic setObject:list forKey:_F(@"%d",index)];
}

//获取节目数据
-(void)updateLiveData
{
    [SVProgressHUD show];
    
    typeof(self) self_ = self;
    [[ProgramModel sharedModel]fetchProgramListWithVip:@"1" currentPage:1 pageSize:1 result:^(NSArray *list, NSString *msg) {
        
        if (list) {
            self_.currentProgram = [list firstObject];
            //:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"
//            [self_.playerView setAVUrl:self_.currentProgram.MEURL];
//            [self_.playerView setAVUrl:@"http://live.3gv.ifeng.com/zixun.m3u8"];
//            [self_.playerView play];
            
            [self_ updateLeaveWords];
            [self_ updateHelpList];
            
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showErrorWithStatus:msg];
        }
        
    }];
}

//获取底部广告数据
-(void)updateADList
{
    typeof(self) self_ = self;
    [[ADModel sharedModel]fetchADListWithChannel:ADChannel code:@"3" result:^(BOOL success, NSArray *array) {
        [self_.buttomADs removeAllObjects];
        [self_.buttomADs addObjectsFromArray:array];
        
        dispatch_async(dispatch_get_main_queue(), ^{
           [self_.radioListView updateRadioListData:self_.buttomADs];
        });
    }];
}


//获取顶部广告数据
-(void)updateTopADList
{
    typeof(self) self_ = self;
    [[ADModel sharedModel]fetchADListWithChannel:ADChannel code:@"4" result:^(BOOL success, NSArray *array) {
        [self_.topADs removeAllObjects];
        [self_.topADs addObjectsFromArray:array];
    }];
}

-(void)starTopAD
{
    [self stopTopAD];
    _topadTimer = [NSTimer timerWithTimeInterval:20.f target:self selector:@selector(exchangeAD:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_topadTimer forMode:NSDefaultRunLoopMode];
}

-(void)stopTopAD
{
    if (_topadTimer) {
        [_topadTimer invalidate];
        _topadTimer = nil;
    }
}

-(void)exchangeAD:(NSTimer *)timer
{
    if ([_topADs count] > 0) {
        if (_topadIndex >= [_topADs count]) {
            _topadIndex = 0;
        }
        ADListItem *item = _topADs[_topadIndex];
        [_adLabel setText:item.text];
        
        _topadIndex++;
    }
    
}


//获取留言列表
-(void)updateLeaveWords
{
    typeof(self) self_ = self;
    [[CompereModel sharedModel]fetchLeaveWordsListWithCmtType:CommentTypeForLiveLeave cmtTarget:self_.currentProgram.programId reqType:RequestTypeAll pageSize:3 currentPage:1 result:^(NSArray *list, NSString *msg) {
        
        [self_ insertOtherInfoData:list index:0];
        
        [self_.tableview reloadData];
    }];
}

//获取便民信息
-(void)updateHelpList
{
    typeof(self) self_ = self;
    [[HelpModel sharedModel]fetchHelpListWithType:@"3" currentPage:1 pageSize:3 result:^(NSArray *list, NSString *msg) {
        [self_ insertOtherInfoData:list index:1];

        [self_.tableview reloadData];
    }];
}

//初始化table
-(void)initializeTableHeaderView
{
    FontSizeButtonObject *btnSetInfo0 = [FontSizeButtonObject new];
    btnSetInfo0.fontSize = 14;
    btnSetInfo0.buttonTitle = @"观众留言";
    btnSetInfo0.buttonTitleDefaultColor = [UIColor grayColor];
    btnSetInfo0.buttonTitleSelectedColor = [UIColor blackColor];
    btnSetInfo0.buttonBackgroudSelectedImage = @"tab_selected_bg.png";
    
    
    
    FontSizeButtonObject *btnSetInfo1 = [FontSizeButtonObject new];
    btnSetInfo1.fontSize = 14;
    btnSetInfo1.buttonTitle = @"便民信息";
    btnSetInfo1.buttonTitleDefaultColor = [UIColor grayColor];
    btnSetInfo1.buttonTitleSelectedColor = [UIColor blackColor];
    btnSetInfo1.buttonBackgroudSelectedImage = @"tab_selected_bg.png";
    
    _switchBarView = [[KKSwitchBarView alloc]initWithFontSizeBtnInfo:@[btnSetInfo0,btnSetInfo1] selectedIndex:0 frame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 36.f)];
    _switchBarView.delegate = self;
    
    UIView *view = [[UIView alloc]initWithFrame:_switchBarView.bounds];
    view.backgroundColor = [UIColor lightGrayColor];
    view.alpha = 0.5;
    [_switchBarView insertSubview:view atIndex:0];
    
    [_tableview setTableHeaderView:_switchBarView];
 
    _otherInfoType = 0;
}

//初始化table
-(void)initializeTableFooterView
{
    _radioListView = _LoadXib(RecommendRadioListView, nil, nil);
    _radioListView.delegate =  self;
    CGRect frame = _radioListView.frame;
    frame.size.width = CGRectGetWidth(self.view.bounds);
    _radioListView.frame = frame;
    
    [_tableview setTableFooterView:_radioListView];
}

#pragma mark - table datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *dataList = [_otherInfoDic objectForKey:_F(@"%d",_otherInfoType)];
    return [dataList count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LiveCellIdentifier"];
    
    NSArray *dataList = [_otherInfoDic objectForKey:_F(@"%d",_otherInfoType)];
    id item = dataList[indexPath.row];
    
    if (_otherInfoType == 0) {
        [cell.textLabel setText:[(LeaveWordItem *)item cmtContent]];
    }else{
        [cell.textLabel setText:[(HelpItem *)item DESCT]];
    }
    
    return cell;
}



#pragma mark - table delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_otherInfoType == 0) {
        if (_currentProgram.programId) {
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Comperes" bundle:nil];
            LeaveWordsViewController *leaveWordsViewController = [board instantiateViewControllerWithIdentifier:@"LeaveWordsViewController"];
            [leaveWordsViewController setPart:InterlocutionPartOfSpectator];
            leaveWordsViewController.cmtTarget = _currentProgram.programId;
            [self.navigationController pushViewController:leaveWordsViewController animated:YES];
        }
        
    }else{
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        RadioHelpLisViewController *radioHelpLisViewController = [board instantiateViewControllerWithIdentifier:@"RadioHelpLisViewController"];
        [radioHelpLisViewController setHeftBarButtonItemShow:YES];
        [self.navigationController pushViewController:radioHelpLisViewController animated:YES];
    }
}

#pragma mark - KKSwitchBarView delegate
-(void)switchBarSelectedIndex:(NSUInteger)index switchBar:(KKSwitchBarView *)switchBar
{
    if (_otherInfoType == index) {
        return;
    }else{
        _otherInfoType = index;
        [_tableview reloadData];
    }
}

#pragma mark - RecommendRadioListView delegate
- (void)didSelectItemAtIndex:(NSInteger)index view:(RecommendRadioListView *)view
{
    NSLog(@"%d",index);
}

#pragma mark - top buttons action
-(IBAction)topButtonsAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 1001://主持人介绍
        {
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Comperes" bundle:nil];
            CompereDetailsViewController *ctrl = [board instantiateViewControllerWithIdentifier:@"CompereDetailsViewController"];
            ctrl.anchorid = _currentProgram.ZCRID;
            [self.navigationController pushViewController:ctrl animated:YES];
        }
            break;
        case 1002://栏目介绍
        {
            
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"ProgramIntroduced" bundle:nil];
            ProgramIntroducedViewController *ctrl = [board instantiateViewControllerWithIdentifier:@"ProgramIntroducedViewController"];
            ctrl.item = _currentProgram;
            [self.navigationController pushViewController:ctrl animated:YES];
        }
            break;
        case 1003://省流量模式
        {
            [self deletePlayView];
            [self creatRadioView];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - bottom buttons action
-(IBAction)bottomButtonsAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 1001://返回首页
        {
            [super navBackAction];
        }
            break;
        case 1002://互动视频
        {
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Live" bundle:nil];
            UIViewController *ctrl = [board instantiateViewControllerWithIdentifier:@"VoiceChatViewController"];
            [self.navigationController pushViewController:ctrl animated:YES];
        }
            break;
        case 1003://我要分享
        {
            
        }
            break;
        case 1004://我要留言
        {
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Comperes" bundle:nil];
            LeaveWordsViewController *leaveWordsViewController = [board instantiateViewControllerWithIdentifier:@"LeaveWordsViewController"];
            [leaveWordsViewController setPart:InterlocutionPartOfSpectator];
            leaveWordsViewController.cmtTarget = _currentProgram.programId;
            [self.navigationController pushViewController:leaveWordsViewController animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 接受到放大视频的通知放大播放视频
-(void)magnifyAVPlayer:(NSNotification *)notification
{
    AVPlayerMagnifiedManager *manager = [AVPlayerMagnifiedManager new];
    manager.manager = self;
    manager.avdata = notification.userInfo;
    [manager play];
}

#pragma mark - RadioViewDelegate
-(void)canceledStreamer:(RadioView *)view
{
    [self deleteRadioView];
    [self creatPlayView];
}

-(void)creatPlayView
{
    //添加视频播放
    if (_playerView) {
        return;
    }
    _playerView = _LoadXib(PlayerView, nil, nil);
    _playerView.frame = _playContentView.bounds;
    [_playContentView addSubview:_playerView];
    
    [_playerView setAutomataPlayWhenReady:YES];
    
    [_playerView setAVUrl:@"http://live.3gv.ifeng.com/zixun.m3u8"];
    [_playerView play];
    
}

-(void)deletePlayView
{
    if (!_playerView) {
        return;
    }
    
    [_playerView removeFromSuperview];
    _playerView = nil;
}

-(void)creatRadioView
{
    if (_radioView) {
        return;
    }
//    Track *track = [Track new];
//    track.audioFileURL = _currentProgram.
    
    //添加语音播放
    _radioView = _LoadXib(RadioView, nil, nil);
    _radioView.delegate = self;
    _radioView.frame = _playContentView.bounds;
    [_radioView setRadioTrack:nil];
    [_playContentView addSubview:_radioView];
}

-(void)deleteRadioView
{
    if (!_radioView) {
        return;
    }
    
    [_radioView removeFromSuperview];
    _radioView = nil;
}

-(void)dealloc
{
    
}


@end
